/*
 * sysmo 客户端异常警告转发到的联系人类
 * Copyright (C) 2009  YuLicheng
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.sysmo.server.node.item;

import java.util.HashMap;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.sysmo.db.DatabaseInterface;
import org.sysmo.db.DbClient;
import org.sysmo.db.DbGraph;
import org.sysmo.db.DbItem;
import org.sysmo.db.DbValue;
import org.sysmo.server.util.ServerSettings;

/**
 * 
 * 此类中封装了警告信息需要被转发到的联系人的信息，包括电子邮件地址等。若需要添加
 * 联系方式，可从此类扩展。
 * <br />
 *
 * 当前版本联系人信息只包括邮件地址。
 *
 * @author YuLicheng
 */
public class WarningContect {

    private String email;
    private DatabaseInterface dbInterface;

    /**
     * 使用E-Mail地址创建警告联系人对象。
     *
     * @param dbInterface 数据访问接口。
     * @param email E-Mail地址。
     */
    public WarningContect(DatabaseInterface dbInterface, String email) {
        this.dbInterface = dbInterface;
        this.email = email;
    }

    /**
     * 设置联系人电子邮件地址。
     *
     * @param email 电子邮件地址。
     */
    public void setEmail(String email) {
        this.email = email;
    }

    /**
     * 返回联系人电子邮件地址。
     *
     * @return 电子邮件地址。
     */
    public String getEmail() {
        return email;
    }

    /**
     * 想此联系人所有联系方式发送警告信息。
     *
     * @param warning 警告信息。
     */
    public synchronized void sendWarning(Warning warning) {
        try {
            Properties props = new Properties();
            HashMap<String, String> map = ServerSettings.settings.settingMap;
            props.put("mail.smtp.host", map.get("/warning-mail/smtp"));
            props.put("mail.smtp.auth", "true");
            Auth auth = new Auth(map.get("/warning-mail/username"),
                    map.get("/warning-mail/password"));
            Session se = Session.getDefaultInstance(props, auth);
            MimeMessage message = new MimeMessage(se);
            message.setFrom(new InternetAddress(map.get("/warning-mail/from")));
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(email));
            message.setSubject(map.get("/warning-mail/title"), "utf-8");
            String clientName;
            DbClient client = dbInterface.query_ClientTable(warning.getNodeID());
            if (client != null) {
                clientName = client.name;
            } else {
                clientName = "未知节点";
            }
            String itemName;
            DbItem item = dbInterface.query_ItemTable(warning.getItemID());
            if (item != null) {
                itemName = item.name;
            } else {
                itemName = "未知监控项";
            }
            String graphName;
            DbGraph graph = dbInterface.query_GraphTable(warning.getGraphID());
            if (graph != null) {
                graphName = graph.name;
            } else {
                graphName = "未知图表";
            }
            String valueName;
            DbValue value = dbInterface.query_ValueTable(warning.getValueID());
            if (value != null) {
                valueName = value.name;
            } else {
                valueName = "未知监控值";
            }
            String msgText = clientName + "." + itemName + "." + graphName
                    + "." + valueName + ":\n" + warning.getMessage();
            message.setText(msgText, "utf-8");
            message.saveChanges();
            Transport.send(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

/**
 * JavaMail用户验证类。
 *
 * @author YuLicheng
 */
class Auth extends Authenticator {
    private String strUser;
    private String strPwd;

    public Auth(String user, String password) {
        this.strUser = user;
        this.strPwd = password;
    }

    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(strUser, strPwd);
    }
}
